/**   
* @Title: RoleService.java 
* @Package com.csis.security.service 
* @Description: TODO
* @author dailey  
* @date 2012-9-28
* @version V1.0   
*/
package com.csis.security.service;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.csis.framework.db.BaseDao;
import com.csis.framework.domain.Condition;
import com.csis.security.domain.Role;
import com.csis.security.domain.RoleFormBean;
import com.csis.system.common.IStaticData;
import com.csis.system.common.convert.Converter.ConvertArray;
import com.csis.system.domain.User;

/**
 * @author dailey
 *
 */
@Service
public class RoleService {
	private Log log = LogFactory.getLog(getClass());
	protected static Document root = null;

	@Resource
	protected BaseDao baseDao;

	/**
	 * 
	 */
	public RoleService() {
		SAXReader reader = null;

		reader = new SAXReader();
		try {
			root = reader.read(getClass().getClassLoader().getResourceAsStream(IStaticData.PATH_XML_MENU_ALL));
		} catch (DocumentException e) {
			throw new IllegalArgumentException(e);
		}
	}

	public List<Role> getAllRoles() {
		return baseDao.query4SingleTable(Role.class, "SELECT * FROM " + IStaticData.TABLE_ROLE);
	}

	public Role load(Integer id) {
		return baseDao.load(Role.class, id);
	}

	public Set<Role> getRolesByUser(User user) {
		if (user != null) {
			return user.getRoles();
		}
		return new HashSet<Role>();
	}

	public List<Role> getRolesByName(String roleName) {
		return baseDao.query4SingleTable(Role.class, "SELECT * FROM " + IStaticData.TABLE_ROLE + " WHERE "
				+ IStaticData.COLUMN_ROLE_ROLENAME + " = ?", roleName);
	}

	@SuppressWarnings("rawtypes")
	public String generateRoleMenu(Set<Role> roles) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		buffer.append("<tree id=\"0\">");
		Integer[] roleIds = new Integer[roles.size() + 1];
		int index = 0;
		roleIds[index++] = 0;
		for (Role role : roles) {
			roleIds[index++] = role.getId();
		}
		List<?> list = root.selectNodes("//role");
		for (Iterator iter = list.listIterator(); iter.hasNext();) {
			Element item = (Element) iter.next();
			Attribute roleIdInXML = item.attribute("roleId");
			if (roleIdInXML == null)
				continue;
			for (Integer roleId : roleIds) {
				if (roleId.longValue() == Integer.parseInt(roleIdInXML.getValue())) {
					List<?> items = item.selectNodes("item");
					for (Iterator _iter = items.listIterator(); _iter.hasNext();) {
						Element e = (Element) _iter.next();
						buffer.append(e.asXML());
					}
				}

			}
		}
		buffer.append("</tree>");
		return buffer.toString();
	}

	public RoleFormBean list(RoleFormBean formBean) {
		String sql = getSearchSql(formBean);

		Condition condition = formBean.getCondition();
		if (condition != null) {
			sql = condition.getCondition(sql);
		}
		// importance
		int maxCount = getMaxCount(formBean);
		formBean.getPage().setMaxCount(maxCount);
		sql = formBean.getPage().perPageSql(sql);
		List<Role> beans = baseDao.query4SingleTable(Role.class, sql);
		formBean.setBeans(beans);
		return formBean;
	}

	/**
	 * @return
	 */
	public int getMaxCount(RoleFormBean formBean) {
		String sql = getSearchSql(formBean);
		return baseDao.getMaxCount(sql);
	}

	/**
	 * @param formBean
	 * @return
	 */
	public String getSearchSql(RoleFormBean formBean) {
		String sql = "SELECT * FROM " + IStaticData.TABLE_ROLE + " WHERE 1=1 ";
		return sql;
	}

	@Transactional
	public void saveRole(Role role) {
		log.info("RoleService>>SaveRole>>" + role);
		if (role.getId() == null) {
			baseDao.persist(role);
		} else {
			baseDao.merge(role);
		}
	}

	@Transactional
	public void update(Role role) {
		log.info("RoleService>>SaveRole>>" + role);
		baseDao.merge(role);
	}

	@Transactional
	public void create(Role role) {
		log.info("RoleService>>SaveRole>>" + role);
		baseDao.persist(role);
	}

	@Transactional
	public void remove(Integer id) {
		baseDao.remove(Role.class, id);
	}

	@Transactional
	public void remove(ConvertArray<Integer> ids) {
		if (ids == null)
			return;
		for (Integer id : ids) {
			remove(id);
		}
	}
}
